# a truly minimal HTTP proxy

import SocketServer
import SimpleHTTPServer
import urllib
import json

PORT = 1234

remoteUrl = 'http://www.marsrutai.lt/API.svc/json'

rules = [
    {
        'requestName': 'GetScopeInfo',
        'func': lambda item: (item[0], 1 if item[0] == 'Version' else item[1]),
        'returnType': 'obj',
        'enabled': True
    },
    {
        'requestName': 'GetSchedules',
        'func': lambda item: (item[0], 'Test' if item[0] == 'TrackName' else item[1]),
        'returnType': 'list',
        'enabled': True
    }
]

# Uses the list composition to make the key value pairs over a dictionary.
dict2list = lambda dic: [(k, v) for (k, v) in dic.iteritems()]

# Use the built in dictionary constructor to convert the list.
list2dict = lambda lis: dict(lis)

class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        print self.path
        
        if self.path.endswith('favicon.ico'):
            self.finish()
            return

        if len(self.path) <= 2:
            self.sendResp('It works!')
            return

        try:
            requestName = self.path.split('/')[2]
        except IndexError:
            requestName = self.path.split('/')[1]
            
        data = json.loads(urllib.urlopen(remoteUrl + self.path).read())

        data = applyRules(data, requestName)

        self.sendResp(json.dumps(data))

    def sendResp(self, resp):
        self.send_response(200)
        self.end_headers()
        self.wfile.write(resp)
        self.finish()

def applyRules(x, requestName):
    for rule in rules:
        if rule['requestName'] == requestName and rule['enabled']:
            if rule['returnType'] == 'list':
                x = [list2dict(map(rule['func'], dict2list(i))) for i in x]
            else:   
                x = list2dict(map(rule['func'], dict2list(x)))
        
    return x

httpd = SocketServer.ThreadingTCPServer(('', PORT), Proxy)
print 'serving at port', PORT
httpd.serve_forever()
